/*
 * Copyright 2012 ETH Zurich, Computer Engineering and Networks Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ch.ethz.vizzly.datareader.gsn;

import java.util.HashMap;

import ch.ethz.vizzly.datatype.ServerSpec;

/**
 * This class keeps references to all instantiated GSN data fetchers. Each
 * data fetcher is responsible for limiting the concurrent access to the
 * referenced GSN server.
 * @author Matthias Keller
 *
 */
public class GsnFetcherInstances {

    /**
     * There is one instance of a data fetcher for each GSN instance.
     * Concurrency is handled within the data fetcher.
     */
    private HashMap<ServerSpec, GsnMultiDataFetcher> dataFetchers = null;
    
    public GsnFetcherInstances() {
        dataFetchers = new HashMap<ServerSpec, GsnMultiDataFetcher>();
    }
    
    public synchronized GsnMultiDataFetcher getMultiDataFetcher(ServerSpec serverSpec) {
        GsnMultiDataFetcher fetcher = dataFetchers.get(serverSpec);
        if(fetcher == null) {
            fetcher = addMultiDataFetcher(serverSpec);
        }
        return fetcher;
    }
    
    private synchronized GsnMultiDataFetcher addMultiDataFetcher(ServerSpec serverSpec) {
        GsnMultiDataFetcher fetcher = dataFetchers.get(serverSpec);
        if(fetcher == null) {
            fetcher = new GsnMultiDataFetcher(serverSpec);
            dataFetchers.put(serverSpec, fetcher);
        }
        return fetcher;
    }
    
}
